using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AdminSG3L.Domain.Entities;
using AdminSG3L.Applicaticn.Dtos;
using AdminSG3L.Applicaticn.ServicesInterface;
using Microsoft.EntityFrameworkCore;
using Serilog;
using AdminSG3L.Infrastructure.Data;
using AdminSG3L.Applicaticn.Commands; // 添加此命名空间以访问ApiResponse

namespace AdminSG3L.Applicaticn.Services;

/// <summary>
/// RoleService 的筛选功能扩展
/// </summary>
public partial class RoleService : IRoleService
{
    /// <summary>
    /// 分页查询角色（带筛选条件）
    /// </summary>
    public async Task<ApiResponse<(IEnumerable<RoleDto> Roles, int TotalCount)>> GetPagedFilteredDtoAsync(
        int pageIndex, int pageSize, RoleFilterDto filter)
    {
        try
        {
            // 先获取角色基本信息，应用筛选条件
            var query = _dbContext.Roles.Where(r => !r.IsDeleted);
            
            // 按名称筛选（模糊搜索）
            if (!string.IsNullOrEmpty(filter.Name))
            {
                query = query.Where(r => r.RoleName.Contains(filter.Name));
            }
            
            // 按编码筛选（模糊搜索）
            if (!string.IsNullOrEmpty(filter.Code))
            {
                query = query.Where(r => r.RoleCode != null && r.RoleCode.Contains(filter.Code));
            }
            
            // 按状态筛选
            // 注意：在这个简化版本中，我们模拟状态筛选
            // 通过RoleCode中是否包含"disabled"来模拟禁用状态
            if (filter.Status.HasValue)
            {
                if (filter.Status.Value == 1)
                {
                    // 启用状态：roleCode不包含"disabled"
                    query = query.Where(r => r.RoleCode == null || !r.RoleCode.Contains("disabled"));
                }
                else
                {
                    // 禁用状态：roleCode包含"disabled"
                    query = query.Where(r => r.RoleCode != null && r.RoleCode.Contains("disabled"));
                }
            }

            var total = await query.CountAsync();
            var roles = await query
                .Skip(pageIndex * pageSize)
                .Take(pageSize)
                .ToListAsync();
            
            // 为每个角色计算用户数量
            var dtos = new List<RoleDto>();
            foreach (var role in roles)
            {
                var userCount = await _dbContext.Users
                    .Where(u => !u.IsDeleted && u.Roles.Any(r => r.Id == role.Id))
                    .CountAsync();
                
                dtos.Add(new RoleDto(role.Id, role.RoleName, role.RoleCode, role.Description, userCount));
            }
            
            Log.Information("带筛选的角色分页查询: pageIndex={PageIndex}, pageSize={PageSize}, " +
                          "filter=[name={Name}, code={Code}, status={Status}], " +
                          "total={Total}, returned={Count}", 
                          pageIndex, pageSize, filter.Name, filter.Code, filter.Status, total, dtos.Count);
            
            return ApiResponse<(IEnumerable<RoleDto>, int)>.Success((dtos, total));
        }
        catch (Exception ex)
        {
            Log.Error(ex, "带筛选条件分页获取角色异常");
            return ApiResponse<(IEnumerable<RoleDto>, int)>.Fail($"带筛选条件分页获取角色异常: {ex.Message}");
        }
    }
}
